﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EShop.Net.Util.Encrypt
{
    /// <summary>
    /// 类    名：EncryptionHelper
    /// 功能描述：加密加密工具类
    /// 创 建 人：十一
    /// 创建时间：2022/12/5 22:50:43 
    /// </summary>
    public static class EncryptionHelper
    {
        #region MD5 加密解密
        /// <summary>
        /// 创建 MD5 的 Key
        /// </summary>
        /// <returns>随机字符串</returns>
        public static string GenerateMD5Key()
        {
            var desCrypto = DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        /// <summary>
        /// MD5 加密
        /// </summary>
        /// <param name="toEncrypt">要加密的字符串</param>
        /// <param name="key">Key 值</param>
        /// <returns>加密后的字符串</returns>
        public static string MD5Encrypt(string toEncrypt, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(toEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        /// <summary>
        /// MD5 解密，只能通过 Key 值解密
        /// </summary>
        /// <param name="toDecrypt">要解密的字符串</param>
        /// <param name="key">要解密的字符串的 Key 值</param>
        /// <returns>解密后的字符串</returns>
        public static string MD5Decrypt(string toDecrypt, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[toDecrypt.Length / 2];
            for (int x = 0; x < toDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(toDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        #endregion
    }
}
